//
//  YMChapter.swift
//  YMSwiftUI
//
//  Created by anscen on 2022/3/31.
//

import UIKit
import HandyJSON
//import SwiftUIX

struct YMChapter :HandyJSON,Hashable{
    
    var bookId    :String = ""
    var chapterId :String = ""
    var title     :String = ""
    var link      :String = ""
    var content   :String?
    var isLock    :Bool   = false
    var isVip     :Bool   = false
    
    
    mutating func mapping(mapper: HelpingMapper) {
         mapper <<< self.chapterId     <-- ["chapterId","_id"]
    }
}
extension YMChapter{
    static func getChapters(_ bookId :String,completion:@escaping ((_ model : YMHistory?) -> ())){
        historyQueue.getData(bookId: bookId, needChapter: true) { model in
            if let model = model,let chapters = model.chapters,chapters.count > 0{
                completion(model)
            }else{
                ApiMoya.request(target: .source(bookId)) { json in
                    guard let listData = [YMSource].deserialize(from: json.rawString()) else { return }
                    if let list = listData as? [YMSource],let source  = list.first{
                        ApiMoya.request(target: .chapters(source.sourceId)) { json in
                            debugPrint(json)
                            let chapters = json["chapters"]
                            var info = YMHistory()
                            info.bookId = bookId
                            info.chapters = chapters.array
                            info.source = source
                            completion(info)
                            historyQueue.updateChapData(bookId: bookId, chapData: (chapters.rawString() ?? "").data(using: .utf8)) { success in
                                
                            }
                            
                        } failure: { error in
                            completion(nil)
                        }
                    }else{
                        completion(nil)
                    }
                } failure: { error in
                    completion(nil)
                }
            }
        }
    }
    static func getContent(bookId :String,
                           link   :String,
                           sucesss:@escaping (_ json : YMContent) ->(),
                           failure:@escaping ((_ error : String)->())){
        ApiMoya.request(target: .content(link), sucesss: { json in
            guard let model = YMContent.deserialize(from: json["chapter"].rawString()) else { return failure("") }
            sucesss(model)
        }, failure: failure)
    }
}
